package com.onlocation.receivers;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

/**
 * Author: Steve Carrell
 * Date: 5/16/12
 */
public abstract class AbstractAlarmReceiver extends BroadcastReceiver {
    public abstract int getBroadcastFlag();
    
    public abstract Class<?> getClassForIntent();

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent broadcast = new Intent();
        broadcast.putExtra("flag", getBroadcastFlag());
        broadcast.setAction(getBroadcastAction());
        context.sendBroadcast(broadcast);
    }
    
    public String getBroadcastAction() {
        return getClassForIntent().getName() + "_BROADCAST";
    }

    public final void startTimer(Context context, int delay) {
        Intent intent = new Intent(context, getClassForIntent());
        PendingIntent pending = PendingIntent.getBroadcast(context, 0, intent, 0);
        AlarmManager alarmMgr =(AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
                delay, pending);
    }

    public final void stopTimer(Context context) {
        Intent intent = new Intent(context, getClassForIntent());
        PendingIntent pending = PendingIntent.getBroadcast(context, 0, intent, 0);
        AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmMgr.cancel(pending);
    }
}
